package com.example.springtxjta.service;

import com.alibaba.fastjson.JSON;
import com.example.springtxjta.dao.CustomerRepository;
import com.example.springtxjta.domain.Customer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CustomerService {

    public static final String NEW_MSG_KEY = "customer:msg:new";
    public static final String REPLY1_MSG_KEY = "customer:msg:reply1";
    public static final String REPLY2_MSG_KEY = "customer:msg:reply2";

    private final CustomerRepository customerRepository;
    private final JmsTemplate jmsTemplate;


    public CustomerService(CustomerRepository customerRepository, JmsTemplate jmsTemplate) {
        this.customerRepository = customerRepository;
        this.jmsTemplate = jmsTemplate;
    }

    @Transient
    public Customer create(Customer customer) {
        customerRepository.save(customer);
        jmsTemplate.convertAndSend(REPLY1_MSG_KEY, JSON.toJSONString(customer));
        return customer;
    }

    @JmsListener(destination = NEW_MSG_KEY)
    public void create(String name) {
        log.info("CustomerService In Annotation by listener create customer");
        Customer customer = new Customer();
        customer.setUsername("Annotation:" + name);
        customer.setPassword("xxxx");
        customerRepository.save(customer);
        jmsTemplate.convertAndSend(REPLY2_MSG_KEY, JSON.toJSONString(customer));
    }

    public List<Customer> getAll() {
        return customerRepository.findAll();
    }
}
